import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Layout from '@/layout/index.vue'
import OrderManagement from '../views/OrderManagement/index.vue'
import ProductManagement from '../views/ProductManagement/index.vue'
import ChannelManagement from '../views/ChannelManagement/index.vue'
import GoodsForm from '../views/ProductManagement/GoodsForm.vue'
import OrdersEdit from '../views/OrderManagement/edit.vue'
import OrdersInfo from '../views/OrderManagement/info.vue'

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
  },
  {
    path: '/admin',
    component: Layout,
    children: [
      {
        path: 'orders',
        name: 'orders',
        component: OrderManagement,
      },
      {
        path: 'orders/edit',
        name: 'ordersEdit',
        component: OrdersEdit,
      },
      {
        path: 'orders/info',
        name: 'ordersInfo',
        component: OrdersInfo,
      },
      {
        path: 'products',
        name: 'products',
        component: ProductManagement,
      },
      {
        path: '/admin/products/form',
        name: 'goodsForm',
        component: GoodsForm,
      },
      {
        path: 'channels',
        name: 'channels',
        component: ChannelManagement,
      },
    ],
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLogin = localStorage.getItem('isLogin')
  const token = localStorage.getItem('token')

  // 如果访问登录页，直接放行
  if (to.path === '/login') {
    // 如果已经登录，重定向到管理页面
    if (isLogin && token) {
      next('/admin/orders')
    } else {
      next()
    }
    return
  }

  // 如果未登录，重定向到登录页
  if (!isLogin || !token) {
    next('/login')
    return
  }

  // 已登录，放行
  next()
})

export default router
